﻿using KBZ.Common;
using Panuon.UI.Silver;
using Panuon.UI.Silver.Core;
using ServiceLibrary.DtoModel.DeskApp;
using ServiceLibrary.DtoModel.DeskApp.pageModel;
using ServiceLibrary.Implements;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace fResApp
{
    public partial class SignInWin : WindowX
    {
        #region Property
        //判断网络状况的方法,返回值true为连接，false为未连接
        [DllImport("wininet")]
        public extern static bool InternetGetConnectedState(out int conState, int reder);
        private string webUrl { get; set; }
        sysUserService userService = new sysUserService();
        #endregion

        public SignInWin()
        {
            InitializeComponent();
        }

        #region Event
        private void WindowX_Loaded(object sender, RoutedEventArgs e)
        {
            VerifyIsActive();
            getAssemblyVersion();
            var _webUrl = ConfigExtensions.Configuration["GroupInfo:webUrl"]; webUrl = _webUrl;
            var _email = ConfigExtensions.Configuration["GroupInfo:email"];
            var _tel = ConfigExtensions.Configuration["GroupInfo:tel"];
            LinkWebTxt.Text = _webUrl;
            linkWebTxt.Text = _webUrl;
            linkTel.Text = _tel;
            txtTel.Text = _tel;
            linkEmal.Text = _email;
            txtEmail.Text = _email;
            ErroeNetBlock.Visibility = Visibility.Collapsed;
            verifyVersionBlock.Visibility = Visibility.Collapsed;
            isRememberpd();
        }
        /// <summary>
        /// 关闭窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CloseWindow_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
        /// <summary>
        /// 重新加载窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReloadWindow_Click(object sender, RoutedEventArgs e)
        {
            VerifyIsActive();
        }
        /// <summary>
        /// 移动窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MoveWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DragMove();
        }
        /// <summary>
        /// 访问官网
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LinkWeb_Click(object sender, RoutedEventArgs e)
        {
            if (VerifyIsActive()) Process.Start(webUrl);
        }
        /// <summary>
        /// 忘记密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnForget_Click(object sender, RoutedEventArgs e)
        {
            if (VerifyIsActive()) Notice.Show("请按照上方的联系方式时联系我们！", "提示", 3, MessageBoxIcon.Info);
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Sign_Click(object sender, RoutedEventArgs e)
        {
            var handler = PendingBox.Show("正在登录中，请稍等...", "", false, this, new PendingBoxConfigurations()
            {
                LoadingForeground = "#5DBBEC".ToColor().ToBrush(),
                ButtonBrush = "#5DBBEC".ToColor().ToBrush(),
                LoadingSize = 50,
                PendingBoxStyle = PendingBoxStyle.Classic,
                FontSize = 15,
            });
            try
            {
                if (VerifyIsActive())
                {
                    var _name = txtUName.Text.Trim();
                    var _pwd = txtUPwd.Password.Trim();
                    if (string.IsNullOrEmpty(_name) || string.IsNullOrEmpty(_pwd))
                    {
                        handler.Close();
                        Notice.Show("请确认您的登录信息输入是否完整！", "提示", 3, MessageBoxIcon.Info);
                        return;
                    }
                    var _uobj = new logicUsers { uName = _name, uPwd = _pwd };
                    var _res = userService.LoginAsync(_uobj).Result;
                    if (_res.statusCode != (int)ApiEnum.Status)
                    {
                        handler.Close();
                        Notice.Show("登录失败，请核实您的登录信息！", "提示", 3, MessageBoxIcon.Info);
                        Logger.Default.ProcessError((int)ApiEnum.Error, "登录失败-->账号【" + _name + "】密钥【" + _pwd + "】。");
                        return;
                    }
                    else
                    {
                        var _uobjinfo = _res.data;
                        if (_uobjinfo == null)
                        {
                            handler.Close();
                            Notice.Show("登录失败，请核实您的登录信息！", "提示", 3, MessageBoxIcon.Info);
                            Logger.Default.ProcessError((int)ApiEnum.Error, "登录信息不存在数据库中-->账号【" + _name + "】密钥【" + _pwd + "】。");
                            return;
                        }
                        //是否记住密码
                        var _jsonPath = Directory.GetCurrentDirectory() + @"\appsettings.json";
                        var isUpjson = new JsonHelper(_jsonPath);
                        if (chkRemember.IsChecked == true)
                        {
                            isUpjson.Update("CusInfo:uname", txtUName.Text, false);
                            isUpjson.Update("CusInfo:upd", txtUPwd.Password, false);
                            isUpjson.Update("CusInfo:isRemember", "true", false);
                        }
                        else
                        {
                            isUpjson.Update("CusInfo:uname", "", false);
                            isUpjson.Update("CusInfo:upd", "", false);
                            isUpjson.Update("CusInfo:isRemember", "", false);
                        }
                        verifyCode.setCatchVal(CacheKey.UTOKETVALUE, _uobjinfo);
                        this.Hide();
                        MainWindow mainWindow = new MainWindow();
                        mainWindow.Show();
                        handler.Close();
                        this.Close();
                    }
                }
                else
                {
                    handler.Close();
                }
            }
            catch (Exception ex)
            {
                handler.Close();
                Logger.Default.Error("", ex);
            }
        }
        #endregion

        #region Function
        /// <summary>
        /// 验证有效性
        /// </summary>
        private bool VerifyIsActive()
        {
            bool isNet = false;
            int i = 0;
            if (InternetGetConnectedState(out i, 0))
            {
                signBlock.Visibility = Visibility.Visible;
                ErroeNetBlock.Visibility = Visibility.Collapsed;
                var _curMachineInfo = MachineUniqueHelper.Value();
                var _uobj = new sysUserDto { OnLineMachineInfo = _curMachineInfo };
                var _res = userService.VerifyIsActive(_uobj).Result;
                if (_res.statusCode != (int)ApiEnum.Status)
                {
                    toAuthor();
                }
                else
                {
                    isNet = true;
                }
            }
            else
            {
                signBlock.Visibility = Visibility.Collapsed;
                ErroeNetBlock.Visibility = Visibility.Visible;
            }
            return isNet;
        }
        private void toAuthor()
        {
            this.Hide();
            AuthorizeWin authorizeWin = new AuthorizeWin();
            authorizeWin.Show();
            this.Close();
        }
        private void isRememberpd()
        {
            var isRemember = ConfigExtensions.Configuration["CusInfo:isRemember"];
            if (!string.IsNullOrEmpty(isRemember) && isRemember.ToLower().Equals("true"))
            {
                chkRemember.IsChecked = true;
                txtUName.Text = ConfigExtensions.Configuration["CusInfo:uname"];
                txtUPwd.Password = ConfigExtensions.Configuration["CusInfo:upd"];
            }
        }
        private void getAssemblyVersion()
        {
            var _versionConfig = ConfigExtensions.Configuration["GroupInfo:AssemblyVersion"];
            if (string.IsNullOrEmpty(_versionConfig)) _versionConfig = "http://bangbangwangluo.com/code.json";
            var _jsonObj = new JsonHelper("");
            var curVers = _jsonObj.Read<VerifyModel>("", true, _versionConfig);
            var vers = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            if (!vers.Equals(curVers.Version))
            {
                verifyVersionBlock.Visibility = Visibility.Visible;
                ErroeNetBlock.Visibility = Visibility.Collapsed;
                signBlock.Visibility = Visibility.Collapsed;
            }
        }
        #endregion
    }
}
